package smlab.media
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	/**
	 * 声音控制器
	 * date:2010.2.23
	 * update:2010.2.23
	 * @author simon
	 *
	 */
	public class SoundController_SM
	{
		private var _channel:SoundChannel;
		private var _position:Number=0;
		private var _sound:Sound;
		private var _volume:Number=1;
		private var _soundtransform:SoundTransform;
		
		public function SoundController_SM($sound:Sound)
		{
			_sound=$sound;
			_channel=_sound.play(0);
			_channel.stop();
		}
		
		/**
		 * 开始播放
		 * @param $position	负数代表从暂停的地方继续播放，其它值代表从该值处开始播放
		 * @param replay	是否重复播放
		 *
		 */
		public function play($position:Number=-1,replay:Boolean=false):void
		{
			if ($position < 0)
			{
			}
			else
			{
				_position=$position;
			}
			_channel=_sound.play(_position);
			_soundtransform=_channel.soundTransform;
			_soundtransform.volume=_volume;
			_channel.soundTransform=_soundtransform;
			
			if(replay){
				_channel.addEventListener(Event.SOUND_COMPLETE,onComplete);
			}
		}
		
		private function onComplete(e:Event):void
		{
			_channel.removeEventListener(Event.SOUND_COMPLETE,onComplete);
			play(0,true);
		}
		
		/**
		 * 停止播放
		 * 
		 */
		public function stop():void
		{
			_position=_channel.position;
			
			if (_channel != null)
			{
				_channel.stop();
				_channel.removeEventListener(Event.SOUND_COMPLETE,onComplete);
			}
		}
		
		/**
		 * 设置音量
		 * @param volume	0静音-1最大
		 * 
		 */
		public function set volume(value:Number):void
		{
			_volume=value;
			_soundtransform=_channel.soundTransform;
			_soundtransform.volume=_volume;
			_channel.soundTransform=_soundtransform;
		}
		
		public function get volume():Number
		{
			return _volume;
		}
		
		public function get position():Number
		{
			return _position;
		}
		
		public function get sound():Sound
		{
			return _sound;
		}
		
		public function get channel():SoundChannel
		{
			return _channel;
		}
	}
}




/* 
//使用范例：
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.media.Sound;

import smlab.sound.SoundController_SM;

public class test extends Sprite
{
private var s:Sound;
private var c:SoundController_SM;

public function test()
{
stage.addEventListener(MouseEvent.CLICK,f);
s=new Sound_OnPosition;
c=new SoundController_SM(s);
}

private function f(e:MouseEvent):void
{
c.volume=1;
c.play(0);
}
}
} 

*/